<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片主体区域 -->
    <el-card>
      <!-- 搜索添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区域 -->
          <div>
            <el-input placeholder="请输入内容" v-model.trim="quertInfo.query" clearable @clear="getUseList">
              <el-button slot="append" icon="el-icon-search" @click="getUseList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <!-- 添加用户 -->
          <!-- 按钮 -->
          <el-button type="primary" size="default" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <template>
        <el-table :data="userList" style="width: 100%" border stripe>
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="username" label="姓名"> </el-table-column>
          <el-table-column prop="email" label="邮箱"> </el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="updataStatus(scope.row)"> </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-row>
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="updateUseShow(scope.row.id)"></el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="showTip(scope.row.id)"></el-button>
                <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                  <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
                </el-tooltip>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="quertInfo.pagenum"
        :page-sizes="[1, 2, 4, 6, 10]"
        :page-size="quertInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户提示框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" append-to-body @close="resetForm('addForm')">
      <!-- 内容主体区域 -->
      <span>
        <el-form ref="addForm" label-width="80px" :model="queryAddUser" :rules="addRules" class="demo-ruleForm">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="queryAddUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" autocomplete="off" v-model="queryAddUser.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" v-model="queryAddUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input type="tel" v-model="queryAddUser.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdd('addForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 更新用户弹出框 -->
    <el-dialog title="修改用户" :visible.sync="updateUseDialog" width="50%" @close="resetUpdataForm">
      <el-form :model="updateForm" ref="updateForm" :rules="addRules" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="updateForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updateForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="updateForm.mobile" type="tel"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateUseDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateUse">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 为用户分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="resetSelet">
      <div>
        <p>当前的用户: {{ setRightUser.username }}</p>
        <p>当前的角色: {{ setRightUser.role_name }}</p>
        <p>
          分配新角色:
          <el-select v-model="roleVule" placeholder="请选择" ref="setRoleSelect">
            <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="SetUserRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 邮箱的校验规则
    var emliRule = (rule, value, callback) => {
      const emailReg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!emailReg.test(value)) {
        callback(new Error('邮箱格式错误'))
      } else {
        callback()
      }
    }
    // 手机号码校验规则
    var telRule = (rule, value, callback) => {
      const telReg = /^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$/
      if (!telReg.test(value)) {
        callback(new Error('手机号码格式错误'))
      } else {
        callback()
      }
    }
    return {
      // 获取用户列表参数
      quertInfo: {
        // 搜索内容
        query: '',
        // 当前页数
        pagenum: 1,
        // 每页显示多少页
        pagesize: 2
      },
      // 用户列表数据
      userList: [],
      total: 0,
      // dialog添加表单的开关
      addDialogVisible: false,
      // dialog修改表单的开关
      updateUseDialog: false,
      // 添加用户表单对象
      queryAddUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单校验规则，复用与更新用户表单
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: emliRule, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: telRule, trigger: 'blur' }
        ]
      },
      // 更新用户表单数据
      updateForm: {},

      // 设置为用户分配角色的对话框的开关
      setRoleDialogVisible: false,

      // 分配角色的用户
      setRightUser: '',

      // 角色列表
      roleList: [],
      // 角色id值
      roleVule: ''
    }
  },
  methods: {
    // 获取用户列表
    async getUseList() {
      const res = await this.$http.get('users', {
        params: this.quertInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败!')
      }
      if (res.data.users.length === 0 && this.quertInfo.pagenum !== 1) {
        this.quertInfo.pagenum--
        return this.getUseList()
      }
      this.userList = res.data.users
      this.total = res.data.total
    },

    // 实现分页功能
    handleSizeChange(val) {
      this.quertInfo.pagesize = val
      this.getUseList()
    },

    handleCurrentChange(val) {
      this.quertInfo.pagenum = val
      this.getUseList()
    },

    // 更新用户数据状态
    async updataStatus(val) {
      const res = await this.$http.put('users/' + val.id + '/state/' + val.mg_state)
      if (res.meta.status !== 200) {
        val.mg_state = !val.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },

    // 实现添加用户功能
    submitAdd(formName) {
      // 再次验证表单
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await this.$http.post('users', this.queryAddUser)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.getUseList()
          this.addDialogVisible = false
        } else {
          return false
        }
      })
    },

    // 实现表单的重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.addDialogVisible = false
    },

    // 展示提示框组件
    async showTip(id) {
      const res = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res === 'confirm') {
        this.deleUser(id)
      } else if (res === 'cancel') {
        this.$message('取消删除')
      }
    },

    // 根据id删除用户,兼容分页功能
    async deleUser(id) {
      const res = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getUseList()
    },

    // 实现表单show
    async updateUseShow(id) {
      // 更具id查询用户信息
      const res = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.updateForm = res.data
      // 控制打开弹出框
      this.updateUseDialog = true
    },

    // 重置updatause表单
    resetUpdataForm() {
      this.$refs.updateForm.resetFields()
      this.updateUseDialog = false
    },

    // 实现更新用户信息的功能
    updateUse() {
      this.$refs.updateForm.validate(async valid => {
        if (!valid) {
          return this.$message.error('表单未验证，请输入表单内容')
        }
        const res = await this.$http.put(`users/${this.updateForm.id}`, this.updateForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.$message.success(res.meta.msg)
        this.getUseList()
        this.updateUseDialog = false
      })
    },
    // 展示分配角色的对话框
    async showSetRoleDialog(user) {
      this.setRightUser = user
      // 在展示对话框前获取角色列表
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.roleList = res.data
      // 展示对话框
      this.setRoleDialogVisible = true
    },

    // 设置用户的角色
    async SetUserRole() {
      if (!this.roleVule) {
        return this.$message.error('请选择一个角色')
      }
      const res = await this.$http.put(`users/${this.setRightUser.id}/role`, {
        rid: this.roleVule
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('设置角色成功')
      this.setRoleDialogVisible = false
      this.getUseList()
    },

    // 重置select
    resetSelet() {
      this.roleVule = ''
    }
  },
  mounted() {
    this.getUseList()
  }
}
</script>

<style lang="less" scoped></style>
